package com.k7k7.cserver.sceneclient;

import com.k7k7.cserver.sceneclient.cmd.SceneServerCmd;
import org.apache.log4j.Logger;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import java.io.*;
import java.net.Socket;
import java.nio.charset.Charset;

/**
 * Created by IntelliJ IDEA.
 * User: Administrator
 * Date: 2009-4-22
 * Time: 9:52:32
 */
public class SceneServerClient extends Thread {
	private Socket socket;
	private BufferedReader reader;
	private PrintWriter writer;
	private Logger log = Logger.getLogger(SceneServerClient.class);

	public SceneServerClient(Socket client) {
		this.socket = client;
		try {
			reader = new BufferedReader(new InputStreamReader(socket
					.getInputStream(), Charset.forName("UTF-8")));
			writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(
					socket.getOutputStream(), Charset.forName("UTF-8"))), true);
		} catch (Exception e) {
			try {
				if (reader != null) {
					reader.close();
				}
				if (writer != null) {
					writer.close();
				}
				socket.close();
			} catch (Exception ignored) {
			}
		}
	}

	@Override
	public void run() {
		String input;
		try {
			while (true) {
				input = reader.readLine().trim();
				if (null == input || input.equals("")) {
					continue;
				}
				handleMsg(input);
			}
		} catch (Exception e) {
			log.info("与场景服务器(" + socket.getInetAddress() + ")连接出现错误!");

			log.error(e.getStackTrace());
			try {
				socket.close();
				reader.close();
				writer.close();
			} catch (Exception ignored) {
			}
		}
	}

	private void handleMsg(String input) {
		Document doc;
		try {
			doc = DocumentHelper.parseText(input);
		} catch (DocumentException e1) {
			log.error("解析XML错误:" + input);
			return;
		}
		Element root = doc.getRootElement();
		log.info(root.asXML());
		String rootName = root.getName();
		if(rootName.equals(SceneServerCmd.register_server)) {
			
		}else if(rootName.equals(SceneServerCmd.unregister_server)){

		}
		log.info("----------------");
	}
}
